<template>
  <VGroup class="h-[32px] relative">
    <el-select
      v-model="platformCurrent"
      placeholder="平台"
      style="width: 180px"
      :disabled="disabled"
      :multiple="multiple"
      collapse-tags
      @change="handleChange('platform', $event)"
      clearable
      filterable
      :filter-method="handleFilter.platform"
      v-if="!defaultPlatform"
    >
      <div v-if="isHandle" class="select-handle py-[4px] px-[8px]">
        <el-button type="primary" link @click="handleCheckAll(item, 'reversion', 'platform')">反选</el-button>
        <el-button type="primary" link @click="handleCheckAll(item, 'all', 'platform')">全选</el-button>
      </div>
      <el-option v-for="item in getOpt(optionsData.platform, valueFilter.platform)" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>

    <el-select
      v-model="siteCurrent"
      multiple
      placeholder="站点"
      style="width: 198px"
      @change="handleChange('site', $event)"
      clearable
      collapse-tags
      filterable
      :filter-method="handleFilter.site"
      :disabled="siteAndshopDisabled"
    >
      <div v-if="isHandle" class="select-handle py-[4px] px-[8px]">
        <el-button type="primary" link @click="handleCheckAll(item, 'reversion', 'site')">反选</el-button>
        <el-button type="primary" link @click="handleCheckAll(item, 'all', 'site')">全选</el-button>
      </div>
      <el-option v-for="item in getOpt(optionsData.sites, valueFilter.site)" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>

    <!-- <el-select
      v-model="shopCurrent"
      multiple
      placeholder="店铺"
      :disabled="!platformCurrent"
      style="width: 196px"
      @change="handleChange('shop', $event)"
      clearable
      collapse-tags
      filterable
      :filter-method="handleFilter.shop"
    >
      <div v-if="isHandle" class="select-handle">
        <el-button type="primary" link @click="handleCheckAll(item, 'reversion', 'shop')">反选</el-button>
        <el-button type="primary" link @click="handleCheckAll(item, 'all', 'shop')">全选</el-button>
      </div>
      <el-option v-for="item in getOpt(optionsData.shop, valueFilter.shop)" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select> -->

    <!-- :confusedPaste="!siteAndshopDisabled ? true : false"
      :paste="!siteAndshopDisabled ? '店铺' : false" -->
    <VSelect
      v-model="shopCurrent"
      placeholder="店铺"
      multiple
      clearable
      collapse-tags
      style="min-width: 198px"
      confusedPaste
      :paste="true"
      :options="shopOption"
      :disabled="siteAndshopDisabled"
      :filter-method="handleFilter.shop"
    >
      <template #default="{ item }">
        <div class="text-[12px]">{{ item.label }}</div>
      </template>
      <template #header v-if="isHandle">
        <div class="select-handle">
          <el-button type="primary" link @click="handleCheckAll(item, 'reversion', 'shop')">反选</el-button>
          <el-button type="primary" link @click="handleCheckAll(item, 'all', 'shop')">全选</el-button>
        </div>
      </template>
    </VSelect>
    <div class="hover-cursor" v-if="siteAndshopDisabled"></div>
  </VGroup>
</template>
<script setup>
import { nextTick, ref, unref } from "vue"
import { apiGetPlatform, getShop } from "@/api/public"
import _, { cloneDeep } from "lodash"

const props = defineProps({
  value: { type: Object, default: () => ({}) },
  multiple: {
    type: Boolean,
    default: true,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  showRule: {
    type: Array,
    default: () => [true, true, true],
  },
  disabled: {
    type: Boolean,
    default: false,
  },

  platform: {
    type: [String, Number, Array],
    // default: () => {},
  },
  site: {
    type: [Array],
    default: () => [],
  },
  shop: {
    type: Array,
    default: () => [],
  },

  isHandle: {
    type: Boolean,
    default: false,
  },
  defaultPlatform: {
    type: Number,
    default: "",
  },
})

const valueFilter = reactive({
  platform: "",
  site: "",
  shop: "",
})
const handleFilter = {
  platform: (v) => {
    valueFilter.platform = v
  },
  site: (v) => {
    valueFilter.site = v
  },
  shop: (v) => {
    valueFilter.shop = v
  },
}
// 站点 店铺 禁用状态
const siteAndshopDisabled = computed(() => {
  if (props.multiple) {
    // 多选
    return !platformCurrent.value || !platformCurrent.value?.length
  } else {
    // 单选
    return !platformCurrent.value
  }
})

const shopOption = computed(() => {
  return optionsData.shop.filter((v) => v.label.toLowerCase().includes(valueFilter.shop.toLowerCase()))
})

const getOpt = (opt = [], val) => {
  return opt?.filter((v) => v.label.toLowerCase().includes(val.toLowerCase())) || []
}

const handleCheckAll = (item, type = "", key = "") => {
  let valueList = []

  if (key == "platform") {
    valueList = getOpt(optionsData.platform, valueFilter.platform)?.map((v) => v.value)
  } else if (key == "site") {
    valueList = getOpt(optionsData.sites, valueFilter.site)?.map((v) => v.value)
  } else if (key == "shop") {
    valueList = getOpt(optionsData.shop, valueFilter.shop)?.map((v) => v.value)
  }
  let attrValue = []
  // // 全选
  if (type == "all") {
    attrValue = valueList
  }
  // 反选
  if (type == "reversion") {
    if (key == "platform") {
      if (valueFilter.platform) {
        attrValue = optionsData.platform.filter((v) => !valueList.includes(v.value))?.map((v) => v.value)
      } else {
        attrValue = optionsData.platform.filter((v) => !platformCurrent.value.includes(v.value))?.map((v) => v.value)
      }
    } else if (key == "site") {
      if (valueFilter.site) {
        attrValue = optionsData.sites.filter((v) => !valueList.includes(v.value))?.map((v) => v.value)
      } else {
        attrValue = optionsData.sites.filter((v) => !siteCurrent.value.includes(v.value))?.map((v) => v.value)
      }
    } else if (key == "shop") {
      if (valueFilter.shop) {
        attrValue = optionsData.shop.filter((v) => !valueList.includes(v.value))?.map((v) => v.value)
      } else {
        attrValue = optionsData.shop.filter((v) => !shopCurrent.value.includes(v.value))?.map((v) => v.value)
      }
    }
  }

  if (key == "platform") {
    emit("update:platform", attrValue)
    handleChange("platform", attrValue, true)
  } else if (key == "site") {
    emit("update:site", attrValue)
  } else if (key == "shop") {
    emit("update:shop", attrValue)
  }
  handleChange(type, attrValue)
}

// const emit = defineEmits(['input'])
const emit = defineEmits(["update:platform", "update:site", "update:shop"])

const platformCurrent = computed({
  get: () => {
    return props.platform
  },
  set: (value) => {
    emit("update:platform", value)
  },
})

const siteCurrent = computed({
  get: () => {
    return props.site
  },
  set: (value) => {
    emit("update:site", value)
  },
})

const shopCurrent = computed({
  get: () => {
    return props.shop
  },
  set: (value) => {
    emit("update:shop", value)
  },
})

const platform = ref()
const site = ref()
const shop = ref()
let ids = reactive({
  platform_id: "",
  site_id: "",
  shop: "",
})

const optionsData = reactive({
  platform: [],
  sites: [],
  shop: [],
})

const options = {
  filterable: true,
  collapseTags: true,
  collapseTagsTooltip: true,
  clearable: true,
  maxCollapseTags: 1,
}

onMounted(() => {
  handleGetPlatforms()
  if (props.defaultPlatform) {
    emit("update:platform", [props.defaultPlatform])
  }
})

const handleGetPlatforms = async () => {
  try {
    const { data } = await apiGetPlatform({ platform_name: " " })
    optionsData.platform = data.map((n) => ({
      label: n.platform_name,
      value: n.platform_id,
    }))
    optionsData.all = data

    setTimeout(() => {
      // 回显  组件待优化
      if (props.platform) {
        handleChange("platform", props.platform, true)
      }
    }, 500)
  } catch (e) {}
}

const getShopOptions = async () => {
  try {
    let params = {
      platform_ids: props.multiple ? platformCurrent.value : platformCurrent.value ? [platformCurrent.value] : [],
      site_ids: siteCurrent.value || [],
    }
    const { data } = (await getShop(params)) || {}

    const _data = data.map((n) => ({
      label: n.shop_name,
      value: n.shop_id,
      site_id: n.site_id,
    }))
    optionsData.shop = cloneDeep(_data)
  } catch (e) {
    shop.value = undefined
    optionsData.shop = []
  }
}

const isArray = (e) => {
  return Object.prototype.toString.call(e) === "[object Array]"
}

const handleCheckOptionsVal = (list, val) => {
  if (isArray(val)) {
    const { multiple } = props
    if (val.length < 1) return val
    if (list.length < 1) return multiple ? "" : []
    const _newVal = multiple ? "" : []
    const _val = JSON.parse(JSON.stringify(val))
    const _list = JSON.parse(JSON.stringify(list))
    for (let i = 0; i < _val.length; i++) {
      const _index = _list.findIndex((v) => v.value === _val[i])
      if (_index > -1) {
        _newVal.push(_val[i])
      }
    }
    return _newVal
  }
}

const handleCheckSites = () => {
  site.value = handleCheckOptionsVal(optionsData.sites, site.value, "site")
}

const handleChange = (type, e, edit = false) => {
  if (type === "platform") {
    let sitesOptions = []
    let _sites = []
    if (isArray(e)) {
      // e.map(n => {
      //   _sites = optionsData.all.fliter(v => v.platform_id === n)?.sites
      // })
      // _sites = optionsData?.all
      //   ?.filter((v) => e.includes(v.platform_id))
      //   .map((v) => v.sites)
      //   .flat()
      _sites = optionsData?.all?.filter((v) => e.includes(v.platform_id))
      _sites = _sites.map((v) => v.sites).flat()
    } else {
      _sites = optionsData.all.find((v) => v.platform_id === e)?.sites
    }
    if (_sites && _sites.length) {
      const _siteOptions = _sites.map((n) => ({
        label: n.site_abbrev,
        value: n.site_id,
      }))
      sitesOptions.push(..._siteOptions)
    }
    optionsData.sites = sitesOptions
    if (!edit) {
      emit("update:site", [])
      emit("update:shop", [])
    }

    nextTick(() => {
      getShopOptions()
    })
  }

  if (type === "site") {
    emit("update:site", e)
    emit("update:shop", [])
    nextTick(() => {
      getShopOptions()
    })
  }
}
</script>

<style scoped lang="scss">
.hover-cursor {
  width: 36px;
  height: 32px;
  position: absolute !important;
  right: -2px;
  &:hover {
    cursor: not-allowed;
  }
}
</style>
